package com.xyulu.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.xyulu.entity.BlogArticleEntity;
import com.xyulu.entity.BlogCommentsEntity;
import com.xyulu.entity.common.*;
import com.xyulu.entity.vo.ArticleQuery;
import com.xyulu.service.*;
import com.xyulu.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author luming
 * @Date 2021/3/2
 * @Version 1.0
 */
@Slf4j
@RestController
@RequiresRoles(RoleConstant.ROOT)
@RequestMapping("/system/article")
public class SysArticleController {

    @Resource
    private BlogArticleService articleService;
    @Resource
    private BlogCategoryService categoryService;
    @Resource
    private BlogTagService tagService;
    @Resource
    private BlogCommentsService commentsService;

    @Value("${file.upload.img}")
    String uploadImgPath;

    /**
     * 获取全部分类
     * @return
     */
    @GetMapping("/getCategories")
    public Result getCategory(){
        return new Result(200,"分类查找成功",categoryService.list());
    }

    /**
     * 获取全部标签
     * @return
     */
    @GetMapping("/getTags")
    public Result getTags(){
        return new Result(200,"标签查找成功",tagService.list());
    }

    /**
     * 保存草稿
     * @param articleEntity
     * @return
     */
    @PostMapping("/draft")
    public Result draftArticle(@RequestBody BlogArticleEntity articleEntity){
        articleEntity.setCreateTime(new Date());
        articleEntity.setUpdateTime(new Date());
        articleEntity.setStatus(CommonField.ARTICLE_DRAFT_STATUS);
        articleService.save(articleEntity);
        return new Result(200,"草稿保存成功");
    }

    /**
     * 发布文章
     * @param articleEntity
     * @return
     */
    @PostMapping("/release")
    public Result releaseArticle(@RequestBody BlogArticleEntity articleEntity){
        articleEntity.setCreateTime(new Date());
        articleEntity.setUpdateTime(new Date());
        articleEntity.setStatus(CommonField.ARTICLE_RELEASE_STATUS);
        articleService.releaseArticle(articleEntity);
        return new Result(200,"文章保存成功");
    }

    /**
     * 修改文章
     * @param articleEntity
     * @return
     */
    @PostMapping("/editArticle")
    public Result editArticle(@RequestBody BlogArticleEntity articleEntity){
        articleService.editArticle(articleEntity);
        return new Result(200,"修改成功");
    }

    /**
     * 文章管理表格数据搜索
     * @param query 搜索条件
     * @return
     */
    @PostMapping("/articleList")
    public Result articleList(@RequestBody ArticleQuery query){
        //构造查询条件
        LambdaQueryWrapper<BlogArticleEntity> lqw = Wrappers.lambdaQuery();
        //时间搜索条件
        if (StringUtils.isNotEmpty(query.getStartTime()) &&
                StringUtils.isNotEmpty(query.getEndTime())) {
            lqw.between(BlogArticleEntity::getCreateTime,query.getStartTime(),query.getEndTime());
        }
        //文章状态 1已发布 和 0草稿
        if (StringUtils.isNotEmpty(query.getStatus())) {
            lqw.eq(BlogArticleEntity::getStatus,query.getStatus());
        }
        //分类条件
        if (query.getCategory() != null) {
            lqw.eq(BlogArticleEntity::getArticleCategory,query.getCategory());
        }
        //模糊搜索
        if (StringUtils.isNotEmpty(query.getTitle())) {
            lqw.like(BlogArticleEntity::getArticleTitle,query.getTitle());
        }

        int count = articleService.count(lqw);
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<BlogArticleEntity> articles = articleService.list(lqw);
        return new Result(200, MessageConstant.ARTICLE_FIND_SUCCESS,count,articles);
    }

    /**
     * 回收站文章列表
     * @param query
     * @return
     */
    @PostMapping("/garbageList")
    public Result garbageList(@RequestBody ArticleQuery query){
        PageHelper.startPage(query.getPage(),query.getLimit());

        LambdaQueryWrapper<BlogArticleEntity> lqw = Wrappers.<BlogArticleEntity>lambdaQuery()
                .eq(BlogArticleEntity::getStatus, 2);
        List<BlogArticleEntity> articles = articleService.list(lqw);
        int count = articleService.count(lqw);

        return new Result(200, MessageConstant.ARTICLE_FIND_SUCCESS,count,articles);
    }

    /**
     * 修改可视状态
     * @param isView
     * @param id
     * @return
     */
    @GetMapping("/changeView")
    public Result changeView(String isView, Integer id){
        Integer view = "true".equals(isView)? 1:0;
        try {
            articleService.updateView(view,id);
            return new Result(200,MessageConstant.ARTICLE_VIEW_CHANGE_SUCCESS);
        } catch (Exception e) {
            log.error("");
        }
        return new Result(400,MessageConstant.ARTICLE_VIEW_CHANGE_FIAIL);
    }

    /**
     * 评论功能开关
     * @param isComment
     * @param id
     * @return
     */
    @GetMapping("/changeComment")
    public Result changeComment(String isComment, Integer id){
        Integer comment = "true".equals(isComment)? 1:0;
        try {
            articleService.updateComment(comment,id);
            return new Result(200,MessageConstant.ARTICLE_COMMENT_CHANGE_SUCCESS);
        } catch (Exception e) {
            log.error("");
        }
        return new Result(400,MessageConstant.ARTICLE_COMMENT_CHANGE_FIAIL);
    }

    /**
     * 回收/批量回收
     * @param ids
     * @return
     */
    @GetMapping("/toRecycleBinByIds")
    public Result toRecycleBinByIds(String ids){
        String[] split = ids.split(",");
        articleService.toRecycleBin(Arrays.asList(split));
        return new Result(200,MessageConstant.ARTICLE_DELETE_FOREVER);
    }

    /**
     * 永久删除
     * @param ids
     * @return
     */
    @GetMapping("/deleteArticleByIds")
    public Result deleteArticleByIds(String ids){
        String[] split = ids.split(",");
//        List<BlogArticleEntity> articles = articleService.listByIds(Arrays.asList(split));
        articleService.removeByIds(Arrays.asList(split));
        //清除文章相关评论
        LambdaQueryWrapper<BlogCommentsEntity> lqw = Wrappers.lambdaQuery();
        for (String id : split) {
            lqw.eq(BlogCommentsEntity::getArticleId,Integer.parseInt(id));
        }
        commentsService.remove(lqw);

        return new Result(200,MessageConstant.ARTICLE_DELETE_TEMP_SUCCESS);
    }

    /**
     * 从回收站恢复文章
     * @param ids
     * @return
     */
    @GetMapping("/recoverArticleByIds")
    public Result recoverArticleByIds(String ids){
        LambdaUpdateWrapper<BlogArticleEntity> lqw = Wrappers.<BlogArticleEntity>lambdaUpdate()
                .eq(BlogArticleEntity::getId, ids)
                .set(BlogArticleEntity::getStatus, 1);
        articleService.update(lqw);
        return new Result(200,MessageConstant.ARTICLE_RECOVER_SUCCESS);
    }

    /**
     * 根据id查找文章
     * @param id
     * @return
     */
    @GetMapping("/getArticleById")
    public Result getArticleById(Integer id){
        BlogArticleEntity article = articleService.getById(id);
        return new Result(200,"",article);
    }

    /**
     * 图片上传
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/coverImgUpload")
    public Result uploadImg(HttpServletRequest request, @RequestParam("file") MultipartFile file){

        String fileName = "";
        String filePath = "";
        try {
            //返回文件路径
            fileName = FileUtil.uploadFile(file, uploadImgPath);
            filePath = "/uploadImg/"+fileName;
            //将文件路径存入到redis中

            return new Result(200,MessageConstant.UPLOAD_SUCCESS,filePath);
        } catch (Exception e) {
            log.error("exception is {}");
        }
        return new Result(400,MessageConstant.UPLOAD_FAIL,filePath);

    }

    /**
     * markdown文件中上传图片 / 粘贴上传
     * @param file
     * @return
     */
    @PostMapping("/markdown/upload")
    public JSONObject mdImg(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file){
        //返回结果对象
        JSONObject result = new JSONObject();
        String fileName = "";
        String filePath = "";
        try {
            fileName = FileUtil.uploadFile(file, uploadImgPath);
            filePath = "/uploadImg/"+fileName;
            result.put("success",1);
            result.put("message",MessageConstant.UPLOAD_SUCCESS);
            result.put("url",filePath);
            return result;
        } catch (Exception e) {
            log.error("exception is {}");
        }
        result.put("success",0);
        result.put("message",MessageConstant.UPLOAD_FAIL);
        return result;
    }

}
